import { Provide } from '@midwayjs/core';
import { BaseService } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { OrderOrderEntity } from '../entity/order';
import { OrderZhongtianEntity } from '../entity/zhongtian';
import { OrderZhongtianGoodsEntity } from '../entity/zhongtianGoods';
import axios from 'axios';
import * as moment from 'moment';

/**
 * 订单模块-店铺信息Service
 */
@Provide()
export class OrderZhongtianService extends BaseService {
    @InjectEntityModel(OrderZhongtianEntity)
    orderZhongtianEntity: Repository<OrderZhongtianEntity>;

    @InjectEntityModel(OrderZhongtianGoodsEntity)
    orderZhongtianGoodsEntity: Repository<OrderZhongtianGoodsEntity>;

    @InjectEntityModel(OrderOrderEntity)
    orderOrderEntity: Repository<OrderOrderEntity>;

    // 中天平台配置，需要根据实际情况修改
    private zhongtianConfig = {
        // host: 'https://ztapitest.ztjoin.com', // 中天平台API地址
        // userid: 'nszht', // 客户对应编码
        // appid: '66576aa656e4458e8356af4aa8b4031a', // 开放平台对应编码

        // host: 'https://ztapitest.ztjoin.com', // 中天平台API地址
        host: 'https://ztapi.ztjoin.com', // 中天平台API地址
        userid: 'bjtyc', // 客户对应编码
        appid: '0c7e6d66bc29405aa6d0071fadbcd819', // 开放平台对应编码
    };

    // 获取商品列表
    async getGoodsList(params) {
        try {
            // 根据参数查询列表 
            const result = await this.orderZhongtianGoodsEntity.find({
                where: {
                    c_ball: params.c_ball,
                    c_pole: params.c_pole,
                }
            });
            return result;
        } catch (error) {
            console.error('获取商品列表失败:', error);
            throw error;
        }
    }

    // 同步商品
    async getGoodsType() {
        try {
            const token = await this.getToken();
            const url = `${this.zhongtianConfig.host}/api/OpenApi`;
            const params = {
                proname: 'Other',
                method: 'GetGoodsType',
                appid: this.zhongtianConfig.appid,
                token: token,
                typecode: '01',
                brandcode: 'XHDD',
                datetime: '0'
            };
            const response = await axios.post(url, params);
            console.log('获取商品品类响应:', response.data);
            // return '';
            if (response.data && response.data.code === '0') {
                // 遍历结果并且存储到数据库中
                for (const item of response.data.result) {
                    console.log('item', item, item.c_cprice);
                    const c_cprice_arr = item.c_cprice.split(',');
                    const c_pprice_arr = item.c_pprice.split(',');
                    const c_zprice_arr = item.c_zprice.split(',');
                    const c_pole_arr = item.c_pole.split(',');
                    // 遍历存储
                    for (let i = 0; i < c_pole_arr.length; i++) {
                        const c_cprice = c_cprice_arr[i];
                        const c_pprice = c_pprice_arr[i];
                        const c_zprice = c_zprice_arr[i];
                        const c_pole = c_pole_arr[i];
                        await this.orderZhongtianGoodsEntity.save({
                            ...item,
                            c_cprice,
                            c_pprice,
                            c_zprice,
                            c_pole,
                        });
                    }
                }
                return true;
            } else {
                throw new Error(`获取商品列表失败: ${response.data?.message || '未知错误'}`);
            }
        } catch (error) {
            console.error('获取商品列表失败:', error);
            throw error;
        }
    }

    // 获取商品品类
    async getGoodsCategory() {
        try {
            const token = await this.getToken();
            const url = `${this.zhongtianConfig.host}/api/OpenApi`;
            const params = {
                proname: 'Common',
                method: 'GetKg',
                appid: this.zhongtianConfig.appid,
                token: token,
                typecode: "0007"
            };
            const response = await axios.post(url, params);
            console.log('获取商品品类响应:', response.data);
            if (response.data && response.data.code === '0') {
                return response.data.result;
            } else {
                throw new Error(`获取商品品类失败: ${response.data?.message || '未知错误'}`);
            }
        } catch (error) {
            console.error('获取商品品类失败:', error);
            throw error;
        }
    }



    
    // gettoken
    async getToken() {
        try {
            // 查询数据库是否已经有token了，并且没有过期
            let orderZhongtian = await this.orderZhongtianEntity.findOne({
                where: {
                    appId: this.zhongtianConfig.appid,
                    userId: this.zhongtianConfig.userid
                }
            });
            if (orderZhongtian && Number(orderZhongtian.tokenExpireTime) > Math.floor(Date.now() / 1000)) {
                return orderZhongtian.token;
            }
            const url = `${this.zhongtianConfig.host}/api/OpenApi`;
            const params = {
                proname: 'CommonOther',
                method: 'GetToken',
                userid: this.zhongtianConfig.userid,
                appid: this.zhongtianConfig.appid
            };

            const response = await axios.post(url, params);
            console.log('orderZhongtian', orderZhongtian)
            // 检查响应是否成功
            if (response.data && response.data.code === '0') {
                // 保存到数据库
                if (orderZhongtian) {
                    orderZhongtian.token = response.data.result.token;
                } else {
                    orderZhongtian = new OrderZhongtianEntity();
                    orderZhongtian.appId = this.zhongtianConfig.appid;
                    orderZhongtian.userId = this.zhongtianConfig.userid;
                    orderZhongtian.token = response.data.result.token;
                }
                
                // expiration_time是7200秒，所以过期时间是7200秒后
                const currentTimeSeconds = Math.floor(Date.now() / 1000); // 当前时间的秒级时间戳
                orderZhongtian.tokenExpireTime = String(Number(currentTimeSeconds) + Number(response.data.result.expiration_time));
                await this.orderZhongtianEntity.save(orderZhongtian);
                return response.data.result.token;
            } else {
                throw new Error(`获取token失败: ${response.data?.message || '未知错误'} `);
            }
        } catch (error) {
            console.error('获取中天平台token失败:', error);
            throw error;
        }
    }

    // 新增顾客
    async createCustomer(data: {
        c_clientname: string;  // 顾客名称
        c_sex: string;         // 性别：M男 F女
        c_mt: string;          // 手机
        c_birthday?: string;   // 生日
        c_address?: string;    // 地址
        c_point?: string;      // 累计积分
        c_dpoint?: string;     // 可用积分
        c_recharge?: string;   // 储值金额
        c_grade?: string;      // 会员等级
        c_number?: string;     // 累计次数
        c_money?: string;      // 累计金额
        c_comment?: string;    // 备注
        c_clientcard?: string; // 卡号
        c_password?: string;   // 密码
        c_home_tel?: string;   // 家庭电话
        c_office_tel?: string; // 办公电话
        c_email?: string;      // 邮箱
    }) {
        try {
            const token = await this.getToken();
            const url = `${this.zhongtianConfig.host}/api/OpenApi`;
            const params = {
                proname: 'Other',
                method: 'CustCreateOrUpdate',
                appid: this.zhongtianConfig.appid,
                token: token,
                type: '0', // 0: 新增 1:修改
                data: data
            };
            console.log(url, params);
            const response = await axios.post(url, params);
            console.log('新增顾客响应:', response.data);
            if (response.data && response.data.code === '0') {
                return response.data.result.c;
            } else {
                throw new Error(`新增顾客失败: ${response.data?.message || '未知错误'}`);
            }
        } catch (error) {
            console.error('新增顾客失败:', error);
            throw error;
        }
    }

    // 获取部门
    async getDept() {
        try {
            const token = await this.getToken();
            const url = `${this.zhongtianConfig.host}/api/OpenApi`;
            const params = {
                proname: 'SystemSet',
                method: 'SearchBm',
                appid: this.zhongtianConfig.appid,
                token: token,
            };
            const response = await axios.post(url, params);
            console.log('获取部门响应:', response.data);
            if (response.data && response.data.code === '0') {
                return response.data.result;
            } else {
                throw new Error(`获取部门失败: ${response.data?.message || '未知错误'}`);
            }
        } catch (error) {
            console.error('获取部门失败:', error);
            throw error;
        }
    }

    // 查询订单
    async queryOrder(order_id) {
        try {
            const token = await this.getToken();
            const url = `${this.zhongtianConfig.host}/api/OpenApi`;
            const order = await this.orderOrderEntity.findOne({
                where: {
                    id: order_id
                }
            });
            if (!order) {
                throw new Error('订单不存在');
            }
            if (!order.zhongtianOrderNo) {
                throw new Error('该订单未下单');
            }
            const params = {
                proname: 'RetailSelect',
                method: 'SelectData',
                appid: this.zhongtianConfig.appid,
                datetype: 5,
                startdate: new Date(order.zhongtianOrderTime).toISOString().slice(0, 10) + ' 00:00:00', // 获取创建时间的当天
                enddate: new Date(order.zhongtianOrderTime).toISOString().slice(0, 10) + ' 23:59:59', // 当前时间
                token: token,
                select: order.zhongtianOrderNo,
                stype: 4
            };
            const response = await axios.post(url, params);
            console.log('查询订单响应:', response.data, url, params);
            if (response.data && response.data.code === '0') {
                return response.data.result;
            } else {
                throw new Error(`查询订单失败: ${response.data?.message || '未知错误'}`);
            }
        } catch (error) {
            console.error('查询订单失败:', error);
            throw error;
        }
    }   

    // 新增订单
    async addOrder(params) {
        try {
            // 根据订单ID获取订单
            const order = await this.orderOrderEntity.findOne({
                where: {
                    id: params.order_id
                }
            });
            if (!order) {
                throw new Error('订单不存在');
            }
            // 如果订单已经下单过则提示已下单
            if (order.zhongtianOrderNo) {
                throw new Error('该订单已下单');
            }

            // 查询柱镜球镜
            const l = await this.orderZhongtianGoodsEntity.findOne({
                where: {
                    id: params.c_goods_l
                }
            });

            const r = await this.orderZhongtianGoodsEntity.findOne({
                where: {
                    id: params.c_goods_r
                }
            });

            if (!l || !r) {
                throw new Error('柱镜球镜不存在');
            }
            const l_code =  l.c_breedcode + l.c_ball + l.c_pole;
            const r_code =  r.c_breedcode + r.c_ball + r.c_pole;

            // 获取部门
            // const dept = await this.getDept();
            // return '';

            const token = await this.getToken();
            const url = `${this.zhongtianConfig.host}/api/OpenApi`;
            const bodyData = {
                "goods": [
                    {
                        // "id": l_code,
                        "id": 'XHDDSMFHLJJP-1.00-0.50ADD1.00',
                        "n": 1,
                        "zk": 0,
                        "np": 0,
                        "p": 0,
                        "lr": 2,
                        "m": 1,
                        // "bp": l.c_pole,
                        "bp": '-0.50',
                        "t": "01"
                    }
                    // {
                    //     // "id": l_code,
                    //     "id": 'XHDDSMFHLJJPGQM-1.00-0.50ADD1.00',
                    //     "n": 1,
                    //     "zk": 0,
                    //     "np": 0,
                    //     "p": 0,
                    //     "lr": 2,
                    //     // "bp": l.c_pole,
                    //     "bp": '-0.50',
                    //     "t": "01"
                    // },
                    // {
                    //     // "id": l_code,
                    //     "id": 'XHDDSMFHLJJPYJM-1.00-0.50ADD1.00',
                    //     "n": 1,
                    //     "zk": 0,
                    //     "np": 0,
                    //     "p": 0,
                    //     "lr": 2,
                    //     // "bp": l.c_pole,
                    //     "bp": '-0.50',
                    //     "t": "01"
                    // },
                    // {
                    //     // "id": l_code,
                    //     "id": 'XHDDSMFHLJJPYJMN-1.00-0.50',
                    //     "n": 1,
                    //     "zk": 0,
                    //     "np": 0,
                    //     "p": 0,
                    //     "lr": 2,
                    //     // "bp": l.c_pole,
                    //     "bp": '-0.50',
                    //     "t": "01"
                    // },
                    // {
                    //     // "id": l_code,
                    //     "id": 'XHDDSMFHLJJPFLGMN-1.00-0.50',
                    //     "n": 1,
                    //     "zk": 0,
                    //     "np": 0,
                    //     "p": 0,
                    //     "lr": 2,
                    //     // "bp": l.c_pole,
                    //     "bp": '-0.50',
                    //     "t": "01"
                    // },
                    // {
                    //     // "id": l_code,
                    //     "id": 'XHDDSMFHLJJPGQN-1.00-0.50',
                    //     "n": 1,
                    //     "zk": 0,
                    //     "np": 0,
                    //     "p": 0,
                    //     "lr": 2,
                    //     // "bp": l.c_pole,
                    //     "bp": '-0.50',
                    //     "t": "01"
                    // },
                    // ,{
                    //     "id": r_code, //  商品
                    //     "n": 1,  // 数量
                    //     "zk": 0, // 折扣
                    //     "np": 0, //原单价
                    //     "p": 0, //实售价
                    //     "lr": 3, // 眼别 2:左眼 3:右眼 其他传空
                    //     "bp": r.c_pole,
                    //     "t": "01"
                    // },
                ],
                "r": {
                        "c_date": "",
                        "c_take": "",
                        "c_type": "0",
                        "c_mode": "零售",
                        "c_sell_man": "001",
                        "c_comment": "北京市北京经济技术开发区景园北街2号42幢2层201"
                    },
                "s": {
                    "sd": moment().format('YYYY-MM-DD HH:mm:ss'),
                    "ss": 0,
                    "ys": 0,
                    "qk": 0,
                    "sf": [
                        {
                            "mode": "微信",
                            "money": 0
                        }
                    ]
                }
            };


            const requestParams = {
                proname: 'Other',
                method: 'SaveOrder',
                appid: this.zhongtianConfig.appid,
                token: token,
                deptcode: "3001",
                sourcecode: order.orderNo,
                data: bodyData
            };
            const response = await axios.post(url, requestParams);
            console.log('新增订单响应:', url, requestParams, response.data);
            if (response.data && response.data.code === '0') {
                // 将获取到的编号保存到订单中
                order.zhongtianOrderNo = response.data.result.c;
                order.zhongtianOrderTime = new Date();
                order.optometricsData = params;
                order.zhongtianOrderRequestData = JSON.stringify(requestParams);
                await this.orderOrderEntity.save(order);
                return response.data.result;
            } else {
                throw new Error(`新增订单失败: ${response.data?.message || '未知错误'}`);
            }
        } catch (error) {
            console.error('新增订单失败:', error);
            throw error;
        }
    }
}
